package cn.lngaosu.lwyd.module.integration.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.core.io.ClassPathResource;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 张恒
 * <p>描述: 微博工具类
 * <p>日期: 2025/6/25 10:59
 */
public class WeiboUtil2 {

    private static HttpClient client = HttpClients.createDefault();
    private static HttpResponse response = null;
    private static HttpGet httpGet = null;
    private static HttpEntity entity = null;

    private static ScriptEngineManager sem = new ScriptEngineManager();
    private static ScriptEngine se = sem.getEngineByName("javascript");
    private static String getJS() {
        try {
            return IOUtils.toString(new ClassPathResource("/js/weibo.js").getInputStream(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    static {
        try {
            String js = getJS();
            se.eval(js);
        } catch (ScriptException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 获取加密后的用户名
     *
     * @return
     */
    public static String getSu(String userId) {
        Invocable inv = (Invocable) se;
        try {
            return (String) inv.invokeFunction("getUs", userId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 登录， 传入加密的用户名
     *
     * @param su
     * @return
     */
    public static JSONObject login(String su, String url, String redirectURI, String userId, String passwd, String clientId) {
        Invocable inv = (Invocable) se;
        httpGet = new HttpGet(
                "https://login.sina.com.cn/sso/prelogin.php?entry=openapi&callback=sinaSSOController.preloginCallBack&su="
                        + su + "&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.18)&_=" + System.currentTimeMillis());

        httpGet.setHeader("Referer",
                url + "?withOfficalFlag=0&passwd=" + passwd
                        + "&action=submit&response_type=code&isLoginSina=0&redirect_uri=" + redirectURI + "&userId="
                        + userId + "&client_id=" + clientId);
        httpGet.setHeader("Host", "login.sina.com.cn");
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0");
        try {
            response = client.execute(httpGet);

            if (response != null) {
                entity = response.getEntity();
                // 执行回调函数
                String preloginCallBack = EntityUtils.toString(entity);
                se.eval(preloginCallBack);
                // 执行自己加入的获取密码方法
                String sp = (String) inv.invokeFunction("getPass", passwd);

                preloginCallBack = preloginCallBack.replace("sinaSSOController.preloginCallBack(", "");
                preloginCallBack = preloginCallBack.substring(0, preloginCallBack.length() - 1);
                JSONObject obj = JSON.parseObject(preloginCallBack);

                // 拼凑登陆数据
                HttpPost loginPost = new HttpPost(
                        "https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)&_" + System.currentTimeMillis()
                                + "&openapilogin=qrcode");
                List<NameValuePair> formData = new ArrayList<>();
                // 应用的App Key
                formData.add(new BasicNameValuePair("entry", "openapi"));
                // 应用的重定向页面
                formData.add(new BasicNameValuePair("gateway", "1"));
                // 模拟登录参数
                // 开发者或测试账号的用户名和密码
                formData.add(new BasicNameValuePair("from", ""));
                formData.add(new BasicNameValuePair("savestate", "0"));
                formData.add(new BasicNameValuePair("useticket", "1"));
                formData.add(new BasicNameValuePair("pagerefer", url));
                formData.add(new BasicNameValuePair("ct", "1800"));
                formData.add(new BasicNameValuePair("s", "1"));
                formData.add(new BasicNameValuePair("vsnf", "1"));
                formData.add(new BasicNameValuePair("vsnval", ""));
                formData.add(new BasicNameValuePair("door", ""));
                //formData.add(new BasicNameValuePair("appkey", appkey));
                formData.add(new BasicNameValuePair("su", su));
                formData.add(new BasicNameValuePair("service", "miniblog"));
                formData.add(new BasicNameValuePair("servertime", obj.getString("servertime")));
                formData.add(new BasicNameValuePair("nonce", obj.getString("nonce")));
                formData.add(new BasicNameValuePair("pwencode", "rsa2"));
                formData.add(new BasicNameValuePair("rsakv", obj.getString("rsakv")));
                formData.add(new BasicNameValuePair("sp", sp));
                formData.add(new BasicNameValuePair("sr", "1920*1080"));
                formData.add(new BasicNameValuePair("encoding", "UTF-8"));
                formData.add(new BasicNameValuePair("cdult", "2"));
                formData.add(new BasicNameValuePair("domain", "weibo.com"));
                formData.add(new BasicNameValuePair("prelt", "201"));
                formData.add(new BasicNameValuePair("returntype", "TEXT"));
                loginPost.setEntity(new UrlEncodedFormEntity(formData, Consts.UTF_8));

                loginPost.setHeader("Referer",
                        url + "?withOfficalFlag=0&passwd=" + passwd
                                + "&action=submit&response_type=code&isLoginSina=0&redirect_uri=" + redirectURI
                                + "&userId=" + userId + "&client_id=" + clientId);
                loginPost.setHeader("Host", "login.sina.com.cn");
                loginPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0");

                response = client.execute(loginPost);

                if (response != null) {

                    entity = response.getEntity();
                    String loginSuccess = EntityUtils.toString(entity);
                    obj = JSON.parseObject(loginSuccess);
                    return obj;
                }

            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取授权的token
     *
     * @param loginObj
     * @return
     */
    public static String getCode(JSONObject loginObj, String url, String redirectURI, String clientId) {
        // 授權登陸
        HttpPost postMethod = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<>();
        // 应用的App Key
        nvps.add(new BasicNameValuePair("client_id", clientId));
        // 应用的重定向页面
        nvps.add(new BasicNameValuePair("redirect_uri", redirectURI));
        // 模拟登录参数
        // 开发者或测试账号的用户名和密码
        nvps.add(new BasicNameValuePair("display", "default"));
        // 猜測是登陸的權證
        nvps.add(new BasicNameValuePair("ticket", loginObj.getString("ticket")));
        // nvps.add(new BasicNameValuePair("uid",
        // obj.getString("uid")));
        nvps.add(new BasicNameValuePair("regCallback", url + "?client_id=" + clientId
                + "&response_type=code&display=default&redirect_uri=" + redirectURI + "&from=&with_cookie="));
        nvps.add(new BasicNameValuePair("isLoginSina", "0"));
        nvps.add(new BasicNameValuePair("action", "login"));
        nvps.add(new BasicNameValuePair("withOfficalFlag", "0"));
        //nvps.add(new BasicNameValuePair("appkey62", appkey));
        postMethod.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        // 添加头信息
        postMethod.setHeader("Referer", url);
        postMethod.setHeader("Host", "api.weibo.com");
        postMethod.setHeader("Origin", "https://api.weibo.com");
        postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");
        postMethod.setHeader("Upgrade-Insecure-Requests", "1");
        postMethod.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1;rv:11.0) Gecko/20100101 Firefox/11.0");

        // client = HttpClients.createDefault();
        response = null;
        try {
            response = client.execute(postMethod);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Header location = response.getFirstHeader("Location");
        if (location != null) {
            String retUrl = location.getValue();
            int begin = retUrl.indexOf("code=");
            if (begin != -1) {
                int end = retUrl.indexOf("&", begin);
                if (end == -1)
                    end = retUrl.length();
                String code = retUrl.substring(begin + 5, end);
                return code;
            }
        }
        return null;
    }
}
